package org.example.c_0_004;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 两个线程间进行数据交换
 */
public class T_Exchanger {

    @Test
    public void test(){
        CountDownLatch countDownLatch = new CountDownLatch(2);
        Exchanger<String> exchanger = new Exchanger<>();
        new Thread(()->{
            String name = "T1";
            try {
                name = exchanger.exchange(name);
//                name = exchanger.exchange(name,1, TimeUnit.SECONDS);
                System.out.println(Thread.currentThread().getName()+"="+name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } /*catch (TimeoutException e) {
                e.printStackTrace();
            } */finally {
                countDownLatch.countDown();
            }
        },"t1").start();
        new Thread(()->{
            String name = "T2";
            try {
                Thread.sleep(2000L);
                name = exchanger.exchange(name);
                System.out.println(Thread.currentThread().getName()+"="+name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDownLatch.countDown();
            }
        },"t2").start();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
